import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_objdetect;
import org.bytedeco.javacv.*;

import javax.swing.*;

import static org.bytedeco.javacpp.opencv_imgproc.*;

public class App {

    public static OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();

    public static void main(String args[]) throws Exception{

        OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);    //初始化摄像头
        grabber.start();   //开始获取摄像头数据
        Frame frameFirst=grabber.grab();//获取摄像头图像的一帧


        CanvasFrame canvas = new CanvasFrame("人脸检测");//新建一个窗口
        canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭窗口时销毁窗口
//        canvas.showImage(frame);//在canvas窗口上显示frame代表的图像



        //------------视频推送
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("e://aa.mp4",frameFirst.imageWidth,frameFirst.imageHeight,0);


        try {
            while (true) {
                if (!canvas.isEnabled()) {//窗口是否关闭
                    grabber.stop();//停止抓取
                    System.exit(0);//退出
                }
                Frame frame = grabber.grab();

                opencv_core.Mat scr = converter.convertToMat(frame);//将获取的frame转化成mat数据类型
                detectFace(scr);//人脸检测
                frame = converter.convert(scr);//将检测结果重新的mat重新转化为frame

                canvas.showImage(frame);//获取摄像头图像并放到窗口上显示， 这里的Frame frame=grabber.grab(); frame是一帧视频图像
                Thread.sleep(50);//50毫秒刷新一次图像
            }
        }
        catch (Exception ex){

        }


    }




    public static opencv_core.Mat detectFace(opencv_core.Mat src) {

        String path = "H:\\openCV\\face\\src\\main\\resources\\haarcascade_frontalface_alt.xml" ;

        opencv_objdetect.CascadeClassifier cascade = new opencv_objdetect.CascadeClassifier(path);//初始化人脸检测器


        opencv_core.Mat grayscr=new opencv_core.Mat();
        cvtColor(src,grayscr,COLOR_BGRA2GRAY);//摄像头是彩色图像，所以先灰度化下
        equalizeHist(grayscr,grayscr);//均衡化直方图
        opencv_core.RectVector faces=new opencv_core.RectVector();
        cascade.detectMultiScale(grayscr, faces);

        for(int i=0;i<faces.size();i++) {
            opencv_core.Rect face_i=faces.get(i);
            rectangle(src, face_i, new opencv_core.Scalar(0, 0, 255, 1));
        }
        return src;
    }


}
